import axios from 'axios'
import { loginOut } from './auth'
import { ElMessage } from 'element-plus'
import { getToken } from './auth'
var instance = axios.create({
  // baseURL: 'http://zcapi.sdjhdz.cn/',
  baseURL: 'https://zcapi.sdlysm.com/',
  timeout: 5000,
  headers: {
    get: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    post: {
      'Content-Type': 'application/json'
    }
  }
})
// 自定义请求头
// instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    Object.assign(config.data, { token: getToken() || '' })
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    return response.data
  },
  function (error) {
    return error.data
  }
)

export const httpPost = (url: string, data = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      url,
      data,
      method: 'post'
    }).then((response) => {
      if ((response as any).code == 0) {
        resolve(response.data)
      } else {
        ElMessage.error((response as any).msg)
        reject((response as any).msg)
        if (
          (response as any).msg == '您未登录或登录已超时 , 请先去登录!' ||
          (response as any).msg == '您的登录已超时 , 请重新登陆!'
        ) {
          setTimeout(() => {
            loginOut()
          }, 1000)
        }
      }
    })
  })
}

export const httpGet = (url: string, params = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      url,
      params,
      method: 'get'
    }).then((response) => {
      if ((response as any).code == 0) {
        resolve(response.data)
      } else {
        ElMessage.error((response as any).msg)
        reject((response as any).msg)
      }
    })
  })
}
